<template>
  <view class="goods-list">
    <view v-for="(goods, i) in goodslist" :key="i" @click="gotoDetail(goods)">

      <!-- 使用组件 把 goods值传递给组件中 -->
      <my-goods :goods="goods"></my-goods>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        //请求参数对象
        queryObj: {
          //查询关键词
          query: '',
          //分类ID
          cid: '',
          //页数索引
          pagenum: 1,
          //每页长度
          pagesize: 10
        },

        //商品列表数据
        goodslist: [],
        //总数量，实现分页
        total: 0,

        //节流阀
        isloading: false


      };
    },
    onLoad(options) {
      //进行赋值，不存在为空
      this.query = options.query || ''
      this.cid = options.cid || ''


      this.getGoodsList()

    },
    methods: {
      //获取商品数据
      async getGoodsList(cd) {
        //打开节流阀
        this.isloading = true
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
        //关闭节流阀
        this.isloading = false

        //如果cd值存在就调用 cd() 关闭下拉刷新效果
        cd && cd()

        if (res.meta.status !== 200) return uni.$showMsg()
        //赋值商品类别数值 新数据与旧数据拼接
        this.goodslist = [...this.goodslist, ...res.message.goods]
        //赋值总数量
        this.total = res.message.total
      },

      gotoDetail(goods) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + goods.goods_id
        })
      }

    },
    onReachBottom() {
      //当前的页码值 * 每页显示多少条数据 >= 总数条数
      if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) {
        return uni.$showMsg('数据加载完毕')
      }

      //如果为 true ，节流阀打开，直接返回
      if (this.isloading) return;

      //然页码值自增加一
      this.queryObj.pagenum++
      //调用 商品列表方法
      this.getGoodsList()
    },
    onPullDownRefresh() {
      //重置关键数据
      this.queryObj.pagenum = 1
      this.queryObj.total = 0
      this.isloading = false
      this.goodslist = []

      //重新发起请求
      this.getGoodsList(() => {
        uni.stopPullDownRefresh()
      })

    }
  }
</script>

<style lang="scss">

</style>